package com.bzyd.mp.datascope;

import com.bzyd.mp.utils.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

/**
 * 数据权限切面
 */
@Slf4j
@Aspect
//@Component
public class DataScopeAspect implements EnvironmentAware {

    private Environment environment;

    /**
     * 切点
     */
    @Pointcut("@annotation(com.bzyd.mp.datascope.DataScope)")
    public void dataScopePointCut() {
    }

    /**
     * 方法执行前 设置DataScopeParam
     * 注意获取注解的方式，@annotation中的值，需要和doBefore方法中的参数名称相同（必须相同，但是名称任意）
     */
    @Before("dataScopePointCut() && @annotation(dataScope)")
    public void doBefore(DataScope dataScope) {
        DataScopeParam dataScopeParam = new DataScopeParam();
        dataScopeParam.setMode(StringUtils.isNotBlank(dataScope.mode()) ? dataScope.mode()
                : environment.getProperty("data-scope.default-mode", String.class, ""));
        dataScopeParam.setDataScopeTableAlias(StringUtils.isNotBlank(dataScope.dataScopeTableAlias()) ? dataScope.dataScopeTableAlias()
                : environment.getProperty("data-scope.default-data-scope-table-alias"));
        dataScopeParam.setDataScopeColumnAlias(StringUtils.isNotBlank(dataScope.dataScopeColumnAlias()) ? dataScope.dataScopeColumnAlias()
                : environment.getProperty("data-scope.default-data-scope-column-alias", String.class, ""));
        dataScopeParam.setCreatorTableAlias(StringUtils.isNotBlank(dataScope.creatorTableAlias()) ? dataScope.creatorTableAlias()
                : environment.getProperty("data-scope.default-creator-table-alias"));
        dataScopeParam.setCreatorColumnAlias(StringUtils.isNotBlank(dataScope.creatorColumnAlias()) ? dataScope.creatorColumnAlias()
                : environment.getProperty("data-scope.default-creator-column-alias", String.class, ""));
        DataScopeContextHolder.set(dataScopeParam);
    }

    /**
     * 方法执行后清楚ThreadLocal
     */
    @After("dataScopePointCut()")
    public void doAfter() {
        DataScopeContextHolder.remove();
    }

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

}
